package com.klikmee.sms.core.base.test.locking;

import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.klikmee.sms.core.model.Provider;

public class FirstObjectLocker implements Runnable {

	@PersistenceContext(name = "SMSCore-PU")
	private EntityManager	entityManager;

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	@Override
	public void run() {
		findAndLock();

	}

	public void findAndLock() {
		System.out.println( "Trying to lock provider 1" );
		Provider provider = this.entityManager.find( Provider.class, new Long( 1 ), LockModeType.PESSIMISTIC_WRITE );
		provider.setName( "Changed during transaction" );
		System.out.println( "Changed name in t1" );
		this.entityManager.merge( provider );
		
		System.out.println( "Trying to wait for 10 seconds" );
		try {

			Thread.sleep( 10000 );
			System.out.println( "Done waiting for 10 seconds in t1" );
		}
		catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
